<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>管理端 - 万万书城</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #333;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .nav {
            background-color: #555;
            overflow: hidden;
        }
        .nav a {
            float: left;
            display: block;
            color: white;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }
        .nav a:hover {
            background-color: #777;
        }
        .content {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .admin-panel {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .search-form {
            margin-bottom: 20px;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
        }
        .search-form input[type="text"] {
            padding: 8px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .search-form button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-form button:hover {
            background-color: #45a049;
        }
        .action-buttons {
            margin-bottom: 20px;
        }
        .action-buttons a {
            display: inline-block;
            padding: 8px 16px;
            background-color: #2196F3;
            color: white;
            text-decoration: none;
            border-radius: 4px;
        }
        .action-buttons a:hover {
            background-color: #0b7dda;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            text-align: left;
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
        }
        .status-normal {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        .status-deleted {
            background-color: #ffebee;
            color: #c62828;
        }
        .btn {
            padding: 6px 12px;
            margin: 0 4px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
        }
        .btn-edit {
            background-color: #ff9800;
            color: white;
        }
        .btn-edit:hover {
            background-color: #e68900;
        }
        .btn-delete {
            background-color: #f44336;
            color: white;
        }
        .btn-delete:hover {
            background-color: #da190b;
        }
        .btn-restore {
            background-color: #4caf50;
            color: white;
        }
        .btn-restore:hover {
            background-color: #45a049;
        }
        .pagination {
            margin-top: 20px;
            text-align: center;
        }
        .pagination a {
            display: inline-block;
            padding: 8px 16px;
            margin: 0 4px;
            text-decoration: none;
            border: 1px solid #ddd;
            color: #333;
            border-radius: 4px;
        }
        .pagination a:hover {
            background-color: #f2f2f2;
        }
        .pagination .active {
            background-color: #2196F3;
            color: white;
            border: 1px solid #2196F3;
        }
        .message {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            font-weight: bold;
        }
        .success-message {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .add-category {
            margin-top: 20px;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>万万书城 - 管理端</h1>
    </div>
    
    <div class="nav">
        <a href="admin?action=list">图书管理</a>
        <a href="admin?action=orderList">订单管理</a>
        <a href="admin?action=userList">用户管理</a>
        <a href="logout" style="float: right;">退出登录</a>
    </div>
    
    <div class="content">
        <div class="admin-panel">
            <!-- 消息提示 -->
            <c:if test="${not empty successMessage}">
                <div class="message success-message">${successMessage}</div>
            </c:if>
            <c:if test="${not empty errorMessage}">
                <div class="message error-message">${errorMessage}</div>
            </c:if>
            
            <!-- 分别处理图书管理、订单管理和用户管理视图 -->
            <c:choose>
                <c:when test="${requestScope.action eq 'userList'}">
                    <!-- 用户管理标题和标签切换 -->
                    <h2>用户管理</h2>
                    
                    <!-- 用户统计信息 -->
                    <div style="display: flex; gap: 20px; margin-bottom: 20px;">
                        <div style="flex: 1; background-color: #e3f2fd; padding: 15px; border-radius: 8px;">
                            <h4>活跃用户总数</h4>
                            <p style="font-size: 24px; font-weight: bold; color: #2196F3;">${activeUserCount}</p>
                        </div>
                        <div style="flex: 1; background-color: #ffebee; padding: 15px; border-radius: 8px;">
                            <h4>已注销用户总数</h4>
                            <p style="font-size: 24px; font-weight: bold; color: #f44336;">${deletedUserCount}</p>
                        </div>
                    </div>
                    
                    <!-- 用户视图切换 -->
                    <div style="margin-bottom: 20px; border-bottom: 1px solid #ddd; padding-bottom: 10px;">
                        <a href="admin?action=userList&view=active" style="padding: 8px 16px; margin-right: 10px; text-decoration: none; ${requestScope.view eq 'active' or empty requestScope.view ? 'background-color: #2196F3; color: white; border-radius: 4px;' : 'color: #333;'} ">活跃用户</a>
                        <a href="admin?action=userList&view=deleted" style="padding: 8px 16px; text-decoration: none; ${requestScope.view eq 'deleted' ? 'background-color: #f44336; color: white; border-radius: 4px;' : 'color: #333;'} ">已注销用户</a>
                    </div>
                    
                    <!-- 用户搜索表单 -->
                    <div class="search-form">
                        <form action="admin" method="get">
                            <input type="hidden" name="action" value="userList">
                            <input type="hidden" name="view" value="${requestScope.view}">
                            <input type="text" name="username" placeholder="输入用户名搜索" value="${username}">
                            <button type="submit">搜索</button>
                        </form>
                    </div>
                    
                    <!-- 活跃用户列表 -->
                    <c:if test="${requestScope.view eq 'active' or empty requestScope.view}">
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>电话号码</th>
                                    <th>地址</th>
                                    <th>订单总数</th>
                                    <th>消费总金额</th>
                                </tr>
                            </thead>
                            <tbody>
                                <c:forEach items="${activeUsers}" var="user">
                                    <tr>
                                        <td>${user.id}</td>
                                        <td>${user.username}</td>
                                        <td>${user.phone}</td>
                                        <td>${user.address}</td>
                                        <td>${user.orderCount}</td>
                                        <td>¥${user.totalSpent}</td>
                                    </tr>
                                </c:forEach>
                            </tbody>
                        </table>
                    </c:if>
                    
                    <!-- 已注销用户列表 -->
                    <c:if test="${requestScope.view eq 'deleted'}">
                        <table>
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <c:forEach items="${deletedUsers}" var="user">
                                    <tr>
                                        <td>${user.id}</td>
                                        <td>${user.username}</td>
                                        <td>
                                            <button class="btn btn-restore" onclick="showRestoreDialog(${user.id}, '${user.username}')">恢复账号</button>
                                        </td>
                                    </tr>
                                </c:forEach>
                            </tbody>
                        </table>
                    </c:if>
                    
                    <!-- 恢复账号对话框 -->
                    <div id="restoreDialog" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.2); z-index: 1000;">
                        <h3>恢复账号</h3>
                        <p>请输入用户 <span id="restoreUsername"></span> 的密码以确认恢复：</p>
                        <form id="restoreForm" action="admin" method="post">
                            <input type="hidden" name="action" value="restoreUser">
                            <input type="hidden" name="userId" id="restoreUserId" value="">
                            <input type="password" name="password" placeholder="输入密码" required style="width: 100%; padding: 8px; margin-bottom: 15px; box-sizing: border-box;">
                            <div style="text-align: right;">
                                <button type="button" onclick="closeRestoreDialog()" style="padding: 8px 16px; background: #ccc; border: none; border-radius: 4px; margin-right: 10px; cursor: pointer;">取消</button>
                                <button type="submit" style="padding: 8px 16px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">确认恢复</button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 遮罩层 -->
                    <div id="overlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 999;"></div>
                    
                    <script>
                        function showRestoreDialog(userId, username) {
                            document.getElementById('restoreUserId').value = userId;
                            document.getElementById('restoreUsername').textContent = username;
                            document.getElementById('restoreDialog').style.display = 'block';
                            document.getElementById('overlay').style.display = 'block';
                        }
                        
                        function closeRestoreDialog() {
                            document.getElementById('restoreDialog').style.display = 'none';
                            document.getElementById('overlay').style.display = 'none';
                        }
                    </script>
                    
                    <!-- 分页 -->
                    <c:if test="${not empty totalPages}">
                        <div class="pagination">
                            <c:if test="${currentPage > 1}">
                                <c:url var="prevUrl" value="admin">
                                    <c:param name="action" value="userList"/>
                                    <c:param name="view" value="${requestScope.view}"/>
                                    <c:param name="page" value="${currentPage - 1}"/>
                                    <c:if test="${not empty username}">
                                        <c:param name="username" value="${username}"/>
                                    </c:if>
                                </c:url>
                                <a href="${prevUrl}">上一页</a>
                            </c:if>
                            
                            <c:forEach begin="1" end="${totalPages}" var="i">
                                <c:url var="pageUrl" value="admin">
                                    <c:param name="action" value="userList"/>
                                    <c:param name="view" value="${requestScope.view}"/>
                                    <c:param name="page" value="${i}"/>
                                    <c:if test="${not empty username}">
                                        <c:param name="username" value="${username}"/>
                                    </c:if>
                                </c:url>
                                <a href="${pageUrl}" class="${currentPage == i ? 'active' : ''}">${i}</a>
                            </c:forEach>
                            
                            <c:if test="${currentPage < totalPages}">
                                <c:url var="nextUrl" value="admin">
                                    <c:param name="action" value="userList"/>
                                    <c:param name="view" value="${requestScope.view}"/>
                                    <c:param name="page" value="${currentPage + 1}"/>
                                    <c:if test="${not empty username}">
                                        <c:param name="username" value="${username}"/>
                                    </c:if>
                                </c:url>
                                <a href="${nextUrl}">下一页</a>
                            </c:if>
                        </div>
                    </c:if>
                </c:when>
                <c:when test="${empty requestScope.orders}">
                    <!-- 图书搜索表单 -->
                    <div class="search-form">
                        <form action="admin" method="post">
                            <input type="hidden" name="action" value="search">
                            <input type="text" name="keyword" placeholder="请输入书名搜索" value="${keyword}">
                            <button type="submit">搜索</button>
                        </form>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="action-buttons">
                        <a href="admin?action=add">添加图书</a>
                    </div>
                    
                    <!-- 图书列表 -->
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>书名</th>
                                <th>作者</th>
                                <th>价格</th>
                                <th>分类</th>
                                <th>库存</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <c:forEach items="${books}" var="book">
                                <tr>
                                    <td>${book.id}</td>
                                    <td>${book.title}</td>
                                    <td>${book.author}</td>
                                    <td>${book.price}</td>
                                    <td>${book.category}</td>
                                    <td>${book.stock}</td>
                                    <td>
                                        <span class="status ${book.deleted ? 'status-deleted' : 'status-normal'}">
                                            ${book.deleted ? '已下架' : '正常'}
                                        </span>
                                    </td>
                                    <td>
                                        <a href="admin?action=edit&id=${book.id}" class="btn btn-edit">修改</a>
                                        <c:if test="${!book.deleted}">
                                            <a href="admin?action=delete&id=${book.id}&delete=true" class="btn btn-delete book-action" onclick="return confirm('确定要下架这本书吗？');">下架</a>
                                        </c:if>
                                        <c:if test="${book.deleted}">
                                            <a href="admin?action=delete&id=${book.id}&delete=false" class="btn btn-restore book-action" onclick="return confirm('确定要上架这本书吗？');">上架</a>
                                        </c:if>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                    
                    <!-- 分页 -->
                    <div class="pagination">
                        <c:if test="${currentPage > 1}">
                            <c:url var="prevUrl" value="admin">
                                <c:param name="action" value="${empty keyword ? 'list' : 'search'}"/>
                                <c:param name="page" value="${currentPage - 1}"/>
                                <c:if test="${not empty keyword}">
                                    <c:param name="keyword" value="${keyword}"/>
                                </c:if>
                            </c:url>
                            <a href="${prevUrl}">上一页</a>
                        </c:if>
                        
                        <c:forEach begin="1" end="${totalPages}" var="i">
                            <c:url var="pageUrl" value="admin">
                                <c:param name="action" value="${empty keyword ? 'list' : 'search'}"/>
                                <c:param name="page" value="${i}"/>
                                <c:if test="${not empty keyword}">
                                    <c:param name="keyword" value="${keyword}"/>
                                </c:if>
                            </c:url>
                            <a href="${pageUrl}" class="${currentPage == i ? 'active' : ''}">${i}</a>
                        </c:forEach>
                        
                        <c:if test="${currentPage < totalPages}">
                            <c:url var="nextUrl" value="admin">
                                <c:param name="action" value="${empty keyword ? 'list' : 'search'}"/>
                                <c:param name="page" value="${currentPage + 1}"/>
                                <c:if test="${not empty keyword}">
                                    <c:param name="keyword" value="${keyword}"/>
                                </c:if>
                            </c:url>
                            <a href="${nextUrl}">下一页</a>
                        </c:if>
                    </div>
                </c:when>
                <c:otherwise>
                    <!-- 订单搜索表单 - 确保始终显示 -->
                    <div class="search-form" style="display:block !important; visibility: visible !important; opacity: 1 !important; margin-bottom: 20px; padding: 20px; background-color: #f9f9f9; border-radius: 8px;">
                        <form action="admin" method="get">
                            <input type="hidden" name="action" value="orderList">
                            <input type="text" name="orderId" placeholder="输入订单号搜索" value="${orderId}">
                            <button type="submit">搜索</button>
                        </form>
                    </div>
                    
                    <!-- 订单统计信息 -->
                    <div style="display: flex; gap: 20px; margin-bottom: 20px;">
                        <div style="flex: 1; background-color: #f0f8ff; padding: 15px; border-radius: 8px;">
                            <h4>订单总数</h4>
                            <p style="font-size: 24px; font-weight: bold; color: #2196F3;">${orderCount}</p>
                        </div>
                        <div style="flex: 1; background-color: #e8f5e9; padding: 15px; border-radius: 8px;">
                            <h4>总销售额</h4>
                            <p style="font-size: 24px; font-weight: bold; color: #4CAF50;">¥${totalSalesAmount}</p>
                        </div>
                    </div>
                    
                    <!-- 订单列表 -->
                    <table>
                        <thead>
                            <tr>
                                <th>订单ID</th>
                                <th>用户ID</th>
                                <th>订单金额</th>
                                <th>订单状态</th>
                                <th>创建时间</th>
                                <th>地址</th>
                                <th>电话</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <c:forEach items="${orders}" var="order">
                                <tr>
                                    <td>${order.id}</td>
                                    <td>${order.userId}</td>
                                    <td>¥${order.totalPrice}</td>
                                    <td>
                                        <span class="status ${order.status == '已完成' ? 'status-normal' : 'status-deleted'}">
                                            ${order.status}
                                        </span>
                                    </td>
                                    <td>${order.createTime}</td>
                                    <td>${order.address}</td>
                                    <td>${order.phone}</td>
                                    <td>
                                        <!-- 订单状态修改 -->
                                        <form action="admin" method="post" style="display: inline;">
                                            <input type="hidden" name="action" value="updateOrderStatus">
                                            <input type="hidden" name="orderId" value="${order.id}">
                                            <select name="status" onchange="this.form.submit()">
                                                <option value="待处理" ${order.status == '待处理' ? 'selected' : ''}>待处理</option>
                                                <option value="已发货" ${order.status == '已发货' ? 'selected' : ''}>已发货</option>
                                                <option value="已完成" ${order.status == '已完成' ? 'selected' : ''}>已完成</option>
                                                <option value="已取消" ${order.status == '已取消' ? 'selected' : ''}>已取消</option>
                                            </select>
                                        </form>
                                    </td>
                                </tr>
                                <!-- 订单项详情 -->
                                <tr>
                                    <td colspan="8">
                                        <div style="padding: 10px; background-color: #f9f9f9; border-radius: 4px; margin-top: 5px;">
                                            <h5>订单详情</h5>
                                            <table style="width: 100%;">
                                                <thead>
                                                    <tr>
                                                        <th style="width: 50%;">图书名称</th>
                                                        <th>单价</th>
                                                        <th>数量</th>
                                                        <th>小计</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <c:forEach items="${order.orderItems}" var="item">
                                                        <tr>
                                                            <td>${item.book.title}</td>
                                                            <td>¥${item.price}</td>
                                                            <td>${item.quantity}</td>
                                                            <td>¥${item.getTotalPrice()}</td>
                                                        </tr>
                                                    </c:forEach>
                                                </tbody>
                                            </table>
                                        </div>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </c:otherwise>
            </c:choose>
            
            <!-- 只在图书管理页面显示分类管理功能 -->
            <c:if test="${empty requestScope.orders and requestScope.action ne 'userList'}">
                <!-- 推荐图书分类 -->
                <div class="add-category" style="margin-top: 30px;">
                    <h3>推荐图书分类</h3>
                    <div style="margin-bottom: 15px;">
                        <p style="color: #666; font-size: 14px;">提示：最多可选5个分类（当前已选${recommendedCount}个），建议选择4种。</p>
                    </div>
                    
                    <!-- 可选分类列表 -->
                    <div style="margin-bottom: 20px;">
                        <h4>可选分类：</h4>
                        <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                            <c:forEach items="${categories}" var="category">
                                <!-- 根据需求，所有图书类都可以被推荐 -->
                                <c:set var="canSelect" value="${category.isRecommended == 0 and recommendedCount < 5}"/>
                                <c:set var="isSelected" value="${category.isRecommended == 1}"/>
                                <c:if test="${!isSelected}">
                                    <form action="admin" method="post" style="display: inline;">
                                        <input type="hidden" name="action" value="updateCategoryRecommendedStatus">
                                        <input type="hidden" name="categoryId" value="${category.id}">
                                        <input type="hidden" name="isRecommended" value="1">
                                        <c:if test="${not empty keyword}">
                                            <input type="hidden" name="keyword" value="${keyword}">
                                        </c:if>
                                        <button type="submit" 
                                                class="btn ${canSelect ? 'btn-edit' : 'btn-delete'}" 
                                                ${!canSelect ? 'disabled style="opacity:0.5; cursor:not-allowed;"' : ''}>
                                            ${category.name}
                                        </button>
                                    </form>
                                </c:if>
                            </c:forEach>
                        </div>
                    </div>
                    
                    <!-- 已推荐分类列表 -->
                    <div>
                        <h4>已推荐分类：</h4>
                        <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                            <c:forEach items="${recommendedCategories}" var="category">
                                <form action="admin" method="post" style="display: inline;">
                                    <input type="hidden" name="action" value="updateCategoryRecommendedStatus">
                                    <input type="hidden" name="categoryId" value="${category.id}">
                                    <input type="hidden" name="isRecommended" value="0">
                                    <c:if test="${not empty keyword}">
                                        <input type="hidden" name="keyword" value="${keyword}">
                                    </c:if>
                                    <button type="submit" class="btn btn-restore">
                                        ${category.name} <span style="color: #f44336;">×</span>
                                    </button>
                                </form>
                            </c:forEach>
                            <c:if test="${empty recommendedCategories}">
                                <p style="color: #999;">暂未推荐任何分类</p>
                            </c:if>
                        </div>
                    </div>
                </div>
                
                <!-- 添加分类 -->
                <div class="add-category">
                    <h3>添加图书分类</h3>
                    <form action="admin" method="post">
                        <input type="hidden" name="action" value="addCategory">
                        <c:if test="${not empty keyword}">
                            <input type="hidden" name="keyword" value="${keyword}">
                        </c:if>
                        <input type="text" name="categoryName" placeholder="请输入分类名称" required>
                        <button type="submit">添加分类</button>
                    </form>
                </div>
            </c:if>
        </div>
    </div>
    <script>
        // 保存当前滚动位置
        function saveScrollPosition() {
            localStorage.setItem('adminScrollPosition', window.scrollY.toString());
        }
        
        // 恢复滚动位置
        document.addEventListener('DOMContentLoaded', function() {
            const savedPosition = localStorage.getItem('adminScrollPosition');
            if (savedPosition) {
                window.scrollTo(0, parseInt(savedPosition));
                // 清除保存的位置，避免影响其他页面
                localStorage.removeItem('adminScrollPosition');
            }
        });
        
        // 为所有操作按钮添加点击事件处理
        document.addEventListener('DOMContentLoaded', function() {
            // 只获取带有book-action类的按钮，这些是图书操作按钮，不包括用户管理部分的恢复账号按钮
            const bookActionButtons = document.querySelectorAll('.btn-delete.book-action, .btn-restore.book-action');
            bookActionButtons.forEach(button => {
                // 移除原来的事件处理方式，使用更简单的方法
                const originalOnClick = button.getAttribute('onclick');
                button.removeAttribute('onclick');
                button.addEventListener('click', function() {
                    // 提取确认消息并显示一次
                    const match = originalOnClick?.match(/confirm\('([^']*)'\)/);
                    if (!match || confirm(match[1])) {
                        saveScrollPosition();
                        // 允许默认导航行为
                        return true;
                    }
                    // 用户取消时阻止导航
                    return false;
                });
            });
            
            // 获取所有推荐分类操作按钮
            const categoryForms = document.querySelectorAll('form[action="admin"]');
            categoryForms.forEach(form => {
                if (form.querySelector('input[name="action"][value="updateCategoryRecommendedStatus"]')) {
                    const button = form.querySelector('button[type="submit"]');
                    if (button) {
                        button.addEventListener('click', function() {
                            saveScrollPosition();
                        });
                    }
                }
            });
        });
    </script>
</body>
</html>